var core = require("core");
var util = core.util;
var wechat = core.wechat;
var crypto = require('crypto');
var send = core.send;
var step = core.step;

var post = function(req, res, next){

    var body = req.body;
    var money = Math.round(body.money * 100);
    var openid = body.openid;
    var mid = body.mid;
    var merchant, order, prepay, SEND;

    var getMerchant = function(){
        var that = this;
        var params = {
            mid : mid
        };
        core.api("merchant/find", params, function(err, doc){
            that.step({err: err, doc: doc});
        });
    };

    var getMerchantEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;

        if(err){
            SEND = new send(200000);
            that.end();
        };
        if(doc.code){
            SEND = doc;
            that.end();
        };

        merchant = doc.docs;

        return true;
    };

    var addOrder = function(){
        var that = this;
        var params = {
            mid : mid,
            money : money,
            openid : openid,
            body : merchant.name +"的无人货架消费"
        };
        core.api("order/add", params, function(err, doc){
            that.step({err: err, doc: doc});
        });
    };

    var addOrderEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;

        if(err){
            SEND = new send(200000);
            that.end();
        };
        if(doc.code){
            SEND = doc;
            that.end();
        };

        order = doc.docs;

        return true;
    };

    var wxOrder = function(){
        var that = this;
        var params = {
            appid : wechat.config.AppID,
            mch_id : wechat.config.mch_id,
            nonce_str : Math.random().toString(36).substr(2, 15),
            body : order.body,
            out_trade_no : order.oid,
            total_fee : money,
            spbill_create_ip : "182.254.139.24",
            notify_url : wechat.config.URL + "pay/note",
            trade_type : "JSAPI",
            openid : openid,
            attach : order.oid
        };

        var sign = util.sort.key(params,true).join("&") + "&key=" + wechat.config.payKey;
        var md5 = crypto.createHash('md5');
        md5.update(sign,"utf8");
        sign = md5.digest('hex').toUpperCase();
        params.sign = sign;

        wechat.api.mch('pay/unifiedorder', params, "body", function(err, doc){
            that.step({err: err, doc: doc});
        });

    };

    var wxOrderEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;

        if(err || doc.errmsg){
            SEND = new send(400000);
            SEND.msg = doc.errmsg || SEND.msg;
            that.end();
        };
        prepay = doc;

        return true;
    };

    var createPaySign = function(){
        var pay ={
            timestamp : parseInt(new Date().getTime() / 1000),
            nonceStr : Math.random().toString(36).substr(2, 15),
            package : 'prepay_id='+prepay.prepay_id,
            signType : "MD5"
        };

        var sign = {
           appId : wechat.config.AppID,
           timeStamp : pay.timestamp,
           nonceStr : pay.nonceStr,
           package : pay.package,
           signType : pay.signType
       };

       sign = util.sort.key(sign,true).join("&") + "&key=" + wechat.config.payKey;
       var md5 = crypto.createHash('md5');
       md5.update(sign,"utf8");
       sign = md5.digest('hex').toUpperCase();

       pay.paySign = sign;

       return pay;

    };

    var end = function(result){
        if(result){
            SEND = new send(0);
            SEND.docs = {
                pay : result,
                oid : order.oid
            };
        }else if(!SEND){
            SEND = new send(300003);
        };

        res.send(SEND);
    }

    step.Step(getMerchant, getMerchantEnd, addOrder, addOrderEnd, wxOrder, wxOrderEnd, createPaySign, end);
};

module.exports = post;
